package jp.sourceforge.akjrcp.audio;

import java.io.File;
import java.io.IOException;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.flvtools.dvdstyler.DVDStylerPage;

public class SoxStretch {
	private String soxPath=null;
	private String ffmpegPath=null;
	//private String soxPath="C:\\Program Files\\sox12181\\sox12181\\sox";
	//private String ffmpegPath="C:\\Program Files\\3GP_Converter034\\cores\\ffmpeg";
	
	private int bitrate=128;
	public double speeds[]={1.8,1.6,1.4,1.2,1.0,0.9,0.8,0.7,0.6,0.5};
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SoxStretch stretch=new SoxStretch();
		
		File inputDir=new File(args[0]);
		File outputDir=new File(args[1]);
		String list[]=inputDir.list();
		if(list!=null){
		for (int i = 0; i < list.length; i++) {
		File f=new File(inputDir,list[i]);
		stretch.makeStretchMP3(f,outputDir);
		}
		}
	}
	public SoxStretch(){
		
	}

	public void makeStretchMP3(File input,File outputDir){
		//input to wav
		try {
			for(int i=0;i<speeds.length;i++){
			File tmp=File.createTempFile("xxx",".wav");
			File tmp2=File.createTempFile("xxx",".wav");
			
			exec(new String[]{ffmpegPath,"-y","-i",input.getAbsolutePath(),tmp.getAbsolutePath()});
			String baseName=chompExtension(input.getName());
			File mp3output=new File(outputDir,baseName+"_"+speeds[i]+".mp3");
			exec(new String[]{soxPath,tmp.getAbsolutePath(),tmp2.getAbsolutePath(),"stretch",""+speeds[i]});
			exec(new String[]{ffmpegPath,"-y","-i",tmp2.getAbsolutePath(),"-ab",""+bitrate,mp3output.getAbsolutePath()});
			
			
			tmp.delete();
			tmp2.delete();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void exec(String args[]) {
		Runtime runtime=Runtime.getRuntime();
		
	
		Process process;
		try {
			for(int i=0;i<args.length;i++){
				//System.out.print("\""+args[i]+"\" ");
			}
			//log.info("\n");
			process = runtime.exec(args);
			StreamMonitor monitor=new StreamMonitor(process);
			monitor.startMonitor();
			process.waitFor();
			//maybe not need.
			//int result=process.waitFor();
			//log.info(""+result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}/* catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/ catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public String chompExtension(String name){
		int index=name.lastIndexOf(".");
		if(index==-1){
			return name;
			
		}else{
			return name.substring(0,index);
		}
	}
	
}
